import pytesseract
from PIL import Image
import time
import os
import numpy
import re


class PicTreat:
    def pic_to_num(self, pic):
        result_list = []
        # 多次取数取出现最多次数字
        text = pytesseract.image_to_string(self.pic_reinforce(pic), lang="eng")
        result_list.append(text[:-2])
        text = pytesseract.image_to_string(self.pic_reinforce(pic), lang="eng")
        result_list.append(text[:-2])
        text = pytesseract.image_to_string(self.pic_reinforce(pic), lang="eng")
        result_list.append(text[:-2])
        text = pytesseract.image_to_string(self.pic_reinforce(pic), lang="eng")
        result_list.append(text[:-2])
        text = pytesseract.image_to_string(self.pic_reinforce(pic), lang="eng")
        result_list.append(text[:-2])
        result = max(result_list, key=result_list.count)
        if '%' in result:
            result = re.search('(\S+?%)', result)[1]
        elif '.' in result:
            result = re.sub('\.', ',', result)
        return result

    def pic_reinforce(self, pic):
        # 使用numpy将图片转化为数字矩阵
        raw_img = Image.open(pic)
        img = numpy.array(raw_img)
        row, col = img.shape[0], img.shape[1]
        # 在图片数字未取完整的部分添加白色空白补充完整。 否则容易取数异常，主要为6多识别出了一个数字4
        added_strip = numpy.array([[240, 247, 255, 255] * row]).reshape((row, 4))
        # 右边加两列
        processed_img = numpy.insert(raw_img, col, added_strip, axis=1)
        processed_img = numpy.insert(processed_img, col + 1, added_strip, axis=1)
        # 下面加一行
        added_strip = numpy.array([[240, 247, 255, 255] * (col + 2)]).reshape((col + 2, 4))
        processed_img = numpy.insert(processed_img, row, added_strip, axis=0)
        # 重新转化为图片
        image = Image.fromarray(processed_img.astype('uint8')).convert('RGB')
        return image

    def get_image(self, element):
        file_name = 'num_pic\\{}.png'.format(str(1000*time.time()))
        element.screenshot(file_name)
        while 1:
            if os.path.exists(file_name):
                break
        return file_name

    def get_num(self, element):
        num_file = self.get_image(element)
        num = self.pic_to_num(num_file)
        if not num:
            # return f"ERROR pic {num_file}"
            return '0'
        return num


if __name__ == '__main__':

    a = PicTreat()
    curr = []
    # # for i in range(10):
    b = a.pic_to_num(r'C:\rb_crawl_inside\num_pic\1634282392807.2546.png')
    # a = Image.open(r'C:\rb_crawl_inside\num_pic\1634192360077.8303.png')
    # w = numpy.array([[240, 247, 255, 255] * 18]).reshape((18, 4))
    # img = numpy.array(a)
    # print(img)
    # print('------------')
    # img = numpy.insert(img, 40, w, axis=1)
    # print(img)
    # print(img.shape)
    # print(dir(a))
    # print(curr)
    print(b)